﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;
using System.Data;

namespace XuaNhapKho
{
    public partial class DonVi : System.Web.UI.Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"] == null)
                {
                    Response.Redirect("/Default.aspx");
                }
                loadGridView();
                loadData();
            }
        }
        public void loadGridView()
        {
            grvDonVi.DataSource = DonViDAO.GetAll();
            grvDonVi.DataBind();
        }
        public void loadData()
        {
            if (Request.QueryString["id"] != null)
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                DataTable dt = DonViDAO.GetBy(id).Tables[0];

                foreach (DataRow rows in dt.Rows)
                {
                    txtDonVi.Text = rows["TenDonVi"].ToString();
                    txtSoLuong.Text = rows["GiaTri"].ToString();
                }

            }
            
        }
        protected void lbtnEdit_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            Response.Redirect("/DonVi.aspx?id="+id);
        }

        protected void lbtnRemove_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            DonViDAO.Delete(id);
            Response.Redirect("/DonVi.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string name = txtDonVi.Text;
            string value = txtSoLuong.Text;

            if (Request.QueryString["id"] == null)
            {
                DonViDAO.Insert(name, int.Parse(value));
                Response.Redirect("/DonVi.aspx");
            }
            else
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                DonViDAO.Update(id,name, int.Parse(value));
                Response.Redirect("/DonVi.aspx");
            }
           
        }

        protected void grvDonVi_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
             grvDonVi.PageIndex = e.NewPageIndex;
             loadGridView();
        }

       
    }
}